﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using Business;
using Data;
using DataAccess.i2iPortalTableAdapters;

public partial class client_Client : @base
{
	private DataTable dtTestInterval = new DataTable();
	private OilReportService ors = new OilReportService();
	
	public void Page_Load(object sender, EventArgs e)
	{
		if (UserDetails == null)
		{
			string jscript =
				"<script language='javascript'  type='text/javascript'> parent.document.location.href= '../Default.aspx'</script>";
			this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key3ClientBlock", jscript);
		}
		if (!IsPostBack)
		{
			if (UserDetails.Is_admin == "Admin")
				Response.Redirect("../admin/Home.aspx");
			else
			{
				report_content.Attributes["src"] = "Welcome2.aspx";
				int i = (int) Session["treeview"];
				if (i == 1)
				{
					//RetrieveInfo();
				}
			}
		}
	}

	protected void RetrieveInfo()
	{
		CreateConn objcon = new CreateConn();
		string client_query = "select clientName, c.client_id AS client from Clients c, Users u"
		                      + " where u.client_id = c.client_id And u.username = '"
		                      + Session["username"] + "'";
		DataTable dt = objcon.SQLConnDataTable(client_query);
		TreeNode node;

		// Add the Root Client
		node = new TreeNode(dt.Rows[0]["clientName"].ToString());
		node.NavigateUrl = "Welcome.aspx";
		node.Target = "report_content";
		tree1.Nodes.Add(node);
		tree1.ExpandDepth = 3;
		// find the subclient
		string query_clientids = "select client_id,clientName from Clients c where c.parent_client_id = " +
		                         dt.Rows[0]["client"];
		CreateConn clientobj = new CreateConn();
		DataTable dt_client = clientobj.SQLConnDataTable(query_clientids);
		if (dt_client.Rows.Count > 0)
		{
			foreach (DataRow dr_client in dt_client.Rows)
			{
				int client_id = Int32.Parse(dr_client["client_id"].ToString());
				string client_name = dr_client["clientName"].ToString();
				TreeNode Node_client = new TreeNode(client_name);
				node.ChildNodes.Add(Node_client);
				string query_oilinfo = "select DISTINCT(site_id),siteName FROM oiltable WHERE client_id = '" + client_id +
				                       "' ORDER BY site_id";
				CreateConn objcon2 = new CreateConn();
				DataTable dt_comp = objcon2.SQLConnDataTable(query_oilinfo);
				if (dt_comp.Rows.Count > 0)
				{
					foreach (DataRow dr_site in dt_comp.Rows)
					{
						String sitename = dr_site["siteName"].ToString();

						TreeNode Node_site = new TreeNode(sitename);
						Node_client.ChildNodes.Add(Node_site);
						Node_site.CollapseAll();
						string query_machines = "SELECT DISTINCT  machine_id,machineName FROM oiltable WHERE(site_id ='" +
						                        dr_site["site_id"] + "')ORDER BY machine_id";
						CreateConn machinobjcon = new CreateConn();
						int machine_status = 0;
						DataTable dt_machines = machinobjcon.SQLConnDataTable(query_machines);

						foreach (DataRow dr_machine in dt_machines.Rows)
						{
							TreeNode Node_machine = new TreeNode(dr_machine["machineName"].ToString());
							Node_site.ChildNodes.Add(Node_machine);
							Node_machine.Collapse();
							String query_components = "SELECT DISTINCT component_id, componentName FROM oiltable WHERE (machine_id='" +
							                          dr_machine["machine_id"] + "') ORDER BY component_id ";
							CreateConn objconncomponents = new CreateConn();
							DataTable dt_components = objconncomponents.SQLConnDataTable(query_components);
							if (dt_components.Rows.Count > 0)
							{
								foreach (DataRow dr_component in dt_components.Rows)
								{
									int component_id = Int32.Parse(dr_component["Component_id"].ToString());
									string query_status = "select status from OilReports where Component_id='" + component_id + "'";
									CreateConn obj_querystatus = new CreateConn();
									try
									{
										DataTable dt_querystatus = obj_querystatus.SQLConnDataTable(query_status);
										if (dt_querystatus != null && dt_querystatus.Rows.Count > 0)
										{
											foreach (DataRow dr_status in dt_querystatus.Rows)
											{
												string component_status = dr_status["status"].ToString();
												int com_sta_int = HelperClass.StatusToInt(component_status);
												if (com_sta_int > machine_status)
												{
													machine_status = com_sta_int;
												}
											}
										}
									}
									catch (Exception e_status)
									{
										Response.Write(e_status.ToString());
									}
									TreeNode Node_component = new TreeNode(dr_component["componentName"].ToString());
									Node_component.NavigateUrl = "oilreport.aspx?id=" + dr_machine["machine_id"] + "&component_id=" +
									                             dr_component["component_id"];
									Node_component.Target = "report_content";
									Node_machine.ChildNodes.Add(Node_component);
								}
								string status_string = machine_status.ToString();
								Node_machine.ImageUrl = HelperClass.GetOilIconByStatusID(status_string);
							}
						}
					}
				}
			}
		}
		else
		{
			string query_oilinfo = "select DISTINCT(site_id),siteName FROM oiltable WHERE client_id = '" + dt.Rows[0]["client"] +
			                       "' ORDER BY site_id";
			CreateConn objcon2 = new CreateConn();
			DataTable dt_comp = objcon2.SQLConnDataTable(query_oilinfo);
			if (dt_comp.Rows.Count > 0)
			{
				foreach (DataRow dr_site in dt_comp.Rows)
				{
					String sitename = dr_site["siteName"].ToString();
					TreeNode Node_site = new TreeNode(sitename);
					node.ChildNodes.Add(Node_site);
					Node_site.CollapseAll();
					string query_machines = "SELECT DISTINCT  machine_id,machineName FROM oiltable WHERE(site_id ='" +
					                        dr_site["site_id"] + "')ORDER BY machine_id";
					CreateConn machinobjcon = new CreateConn();
					int machine_status = 0;
					DataTable dt_machines = machinobjcon.SQLConnDataTable(query_machines);

					foreach (DataRow dr_machine in dt_machines.Rows)
					{
						TreeNode Node_machine = new TreeNode(dr_machine["machineName"].ToString());
						Node_site.ChildNodes.Add(Node_machine);
						Node_machine.Collapse();
						String query_components = "SELECT DISTINCT component_id, componentName FROM oiltable WHERE (machine_id='" +
						                          dr_machine["machine_id"] + "') ORDER BY component_id ";
						CreateConn objconncomponents = new CreateConn();
						DataTable dt_components = objconncomponents.SQLConnDataTable(query_components);
						if (dt_components.Rows.Count > 0)
						{
							foreach (DataRow dr_component in dt_components.Rows)
							{
								int component_id = Int32.Parse(dr_component["Component_id"].ToString());
								string query_status = "select status from OilReports where Component_id='" + component_id + "'";
								CreateConn obj_querystatus = new CreateConn();
								try
								{
									DataTable dt_querystatus = obj_querystatus.SQLConnDataTable(query_status);
									if (dt_querystatus != null && dt_querystatus.Rows.Count > 0)
									{
										foreach (DataRow dr_status in dt_querystatus.Rows)
										{
											string component_status = dr_status["status"].ToString();
											int com_sta_int = HelperClass.StatusToInt(component_status);
											if (com_sta_int > machine_status)
											{
												machine_status = com_sta_int;
											}
										}
									}
								}
								catch (Exception e_status)
								{
									Response.Write(e_status.ToString());
								}
								TreeNode Node_component = new TreeNode(dr_component["componentName"].ToString());
								Node_component.NavigateUrl = "oilreport.aspx?id=" + dr_machine["machine_id"] + "&component_id=" +
								                             dr_component["component_id"];
								Node_component.Target = "report_content";
								Node_machine.ChildNodes.Add(Node_component);
							}
							string staus_str = machine_status.ToString();
							Node_machine.ImageUrl = HelperClass.GetOilIconByStatusID(staus_str);
						}
					}
				}
			}
		}
	}

	protected void Generate_TreeView()
	{
		try
		{
			var objcon = new CreateConn();
			string client_query = "select clientName, c.client_id AS client from Clients c, Users u"
			                      + " where u.client_id = c.client_id And u.username = '"
			                      + Session["username"].ToString() + "'";
			DataTable dt = objcon.SQLConnDataTable(client_query);
			TreeNode node;

			// Add the Root Client
			node = new TreeNode(dt.Rows[0]["clientName"].ToString());
			node.SelectAction = TreeNodeSelectAction.SelectExpand;
			node.NavigateUrl = "Welcome.aspx";
			node.Target = "report_content";

			tree1.Nodes.Add(node);

			// find the subclient
			objcon = new CreateConn();
			string query1 = "select clientName from Clients c where c.parent_client_id = " + dt.Rows[0]["client"];
			DataTable dt1 = objcon.SQLConnDataTable(query1);

			if (dt1.Rows.Count > 0)
			{
				// Add the subclient in main client
				TreeNode man = new TreeNode();
				for (int j = 0; j < tree1.Nodes.Count; j++)
				{
					man = tree1.Nodes[j];

					foreach (DataRow dr in dt1.Rows)
					{
						TreeNode node1 = new TreeNode(dr["clientName"].ToString());
						node1.SelectAction = TreeNodeSelectAction.SelectExpand;
						node1.NavigateUrl = "#";
						man.ChildNodes.Add(node1);
					}
				}

				TreeNode thirdnode = new TreeNode();
				for (int k = 0; k < man.ChildNodes.Count; k++)
				{
					thirdnode = man.ChildNodes[k];
					objcon = new CreateConn();
					string query_site = "select siteName from Sites s, Clients c where c.client_id = s.client_id and c.clientName='" +
					                    thirdnode.Text + "'";
					DataTable dt_sites = objcon.SQLConnDataTable(query_site);

					foreach (DataRow dr in dt_sites.Rows)
					{
						TreeNode node1 = new TreeNode(dr["siteName"].ToString());
						node1.SelectAction = TreeNodeSelectAction.SelectExpand;
						node1.NavigateUrl = "#";
						thirdnode.ChildNodes.Add(node1);
						thirdnode.CollapseAll();
					}

					for (int l = 0; l < thirdnode.ChildNodes.Count; l++)
					{
						TreeNode fourthnode = thirdnode.ChildNodes[l];
						String siteName = fourthnode.Text;
						objcon = new CreateConn();
						string query2 =
							"select machineName, machine_id, client_id from Machines m, Sites s where s.site_id = m.site_id AND m.status = 'Activated' and s.siteName='" +
							fourthnode.Text + "'";
						DataTable dt2 = objcon.SQLConnDataTable(query2);

						foreach (DataRow dr in dt2.Rows)
						{
							String machinename = dr["machineName"].ToString();
							String machineid = dr["machine_id"].ToString();
							String client_id = dr["client_id"].ToString();
							TreeNode node1 = new TreeNode(dr["machineName"].ToString());
							node1.SelectAction = TreeNodeSelectAction.SelectExpand;

							node1.NavigateUrl = "Vibration_Report.aspx?id=" + machineid + "&client_id =" + client_id + "&machineName=" +
							                    machinename;
							node1.Target = "report_content";
							node1.ImageUrl = GetIcon(machineid);
							fourthnode.ChildNodes.Add(node1);
							fourthnode.CollapseAll();
						}
					}
				}
			}
			else
			{
				TreeNode thirdnode = new TreeNode();
				for (int k = 0; k < tree1.Nodes.Count; k++)
				{
					thirdnode = tree1.Nodes[k];
					objcon = new CreateConn();
					string query_site = "select siteName from Sites s, Clients c where c.client_id = s.client_id and c.clientName='" +
					                    thirdnode.Text + "'";
					DataTable dt_sites = objcon.SQLConnDataTable(query_site);

					foreach (DataRow dr in dt_sites.Rows)
					{
						TreeNode node1 = new TreeNode(dr["siteName"].ToString());
						node1.SelectAction = TreeNodeSelectAction.SelectExpand;
						node1.NavigateUrl = "#";
						thirdnode.ChildNodes.Add(node1);
						thirdnode.CollapseAll();
					}

					for (int l = 0; l < thirdnode.ChildNodes.Count; l++)
					{
						TreeNode fourthnode = thirdnode.ChildNodes[l];
						String siteName = fourthnode.Text;
						objcon = new CreateConn();
						string query2 =
							"select machineName, machine_id, client_id from Machines m, Sites s where s.site_id = m.site_id AND m.status = 'Activated' and s.siteName='" +
							fourthnode.Text + "'";
						DataTable dt2 = objcon.SQLConnDataTable(query2);

						foreach (DataRow dr in dt2.Rows)
						{
							String machinename = dr["machineName"].ToString();
							String machineid = dr["machine_id"].ToString();
							String client_id = dr["client_id"].ToString();
							TreeNode node1 = new TreeNode(dr["machineName"].ToString());
							node1.SelectAction = TreeNodeSelectAction.SelectExpand;
							node1.NavigateUrl = "Vibration_Report.aspx?id=" + machineid + "&client_id=" + client_id + "&machineName=" +
							                    machinename;
							node1.Target = "report_content";
							fourthnode.ChildNodes.Add(node1);
							fourthnode.CollapseAll();
						}
					}
				}
			}
		}
		catch (Exception err)
		{
			Console.Write("Err msg:" + err.Message);
		}
	}

	protected string GetIcon(string machineID)
	{
		string src = String.Empty;
		string query = "SELECT   MAX(status_id) AS status_id"
		               + " FROM      ComponentStatus"
		               + " WHERE   (component_id IN"
		               + " (SELECT   component_id"
		               + " FROM      Components"
		               + " WHERE   (machine_id = '" + machineID + "'))) AND (dateRecorded IN"
		               + " (SELECT   MAX(dateRecorded) AS dateRecorded"
		               + " FROM      ComponentStatus AS ComponentStatus_1"
		               + " WHERE   (component_id in (select component_id From Components WHERE machine_id='" + machineID +
		               "'))))";
		CreateConn objcon = new CreateConn();
		DataTable dt = objcon.SQLConnDataTable(query);
		foreach (DataRow dr in dt.Rows)
		{
			string statusID = dr["status_id"].ToString();
			src = HelperClass.GetOilIconByStatusID(statusID);
		}
		return src;
	}

	protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
	{
		Session.Abandon();
		Session.Contents.RemoveAll();
		FormsAuthentication.SignOut();
	}

	protected void LinkButton2_Click(object sender, EventArgs e)
	{
		Server.Transfer("Main.aspx");
	}

	protected void Tree1TreeNodePopulate(object sender, TreeNodeEventArgs e)
	{
		switch (e.Node.Depth)
		{
			case 0:
				// Populate the first-level nodes.
				PopulateCompany(e.Node);
				break;
			case 1:
				// Populate the second-level nodes.
				//PopulateSites(e.Node);
				break;
			case 2:
				// Populate the second-level nodes.
				break;
			case 3:
				// Populate the second-level nodes.
				break;
		}
	}

	private void PopulateComponents(TreeNode node, int machineID)
	{
		ComponentsTableAdapter adapter = new ComponentsTableAdapter();
		var Components = adapter.GetDataByMachineID(machineID);
		foreach (var components in Components)
		{
			var treeNode = new TreeNode(components["componentName"].ToString());
			treeNode.NavigateUrl = "oilreport.aspx?id=" + components["machine_id"] + "&component_id=" +
			                       components["component_id"];
			treeNode.Target = "report_content";
			node.ChildNodes.Add(treeNode);
		}
	}

	private void PopulateMachines(TreeNode node, int siteID)
	{
		MachinesTableAdapter adapter = new MachinesTableAdapter();
		var Machines = adapter.GetDataBySiteID(siteID);
		foreach (var machine in Machines)
		{
			if (machine["status"].ToString().Equals("Deactivated")) continue;
			var treeNode = new TreeNode(machine["machineName"].ToString());
			node.ChildNodes.Add(treeNode);
			int machineID = 0;
			Int32.TryParse(machine["machine_id"].ToString(), out machineID);
			PopulateComponents(treeNode, machineID);
		}
	}

	private void PopulateSites(TreeNode node, int clientID)
	{
		SitesOnClientsTableAdapter adapter = new SitesOnClientsTableAdapter();
		var Sites = adapter.GetDataBy(clientID);
		foreach (var site in Sites)
		{
			var treeNode = new TreeNode(site["siteName"].ToString());
			node.ChildNodes.Add(treeNode);
			int site_id = 0;
			Int32.TryParse(site["site_id"].ToString(), out site_id);
			PopulateMachines(treeNode, site_id);
		}
		node.CollapseAll();
	}

	private void PopulateCompany(TreeNode node)
	{
		var companyNode = new TreeNode(ClientDetails.ClientName);
		node.ChildNodes.Add(companyNode);
		if (HasTestIntervals(ClientDetails.ClientID))
		{
			PopulateTestInterval(companyNode, ClientDetails.ClientID);
			return;
		}
		if (ClientDetails.ParentClientID == 0)
		{
			if (PopulateSubCompanies(node))
			{
				return;
			}
		}
		PopulateSites(companyNode, ClientDetails.ClientID);
		node.CollapseAll();
	}

	private void PopulateTestInterval(TreeNode node, int clientID)
	{
		foreach (Data.i2iPortal.TestInterValRow row in dtTestInterval.Rows)
		{
			var treeNode = new TreeNode(row["Name"].ToString());
			node.ChildNodes.Add(treeNode);
			int intervalId = 0;
			Int32.TryParse(row["Interval_Id"].ToString(), out intervalId);
			PopulateMachinesWithInterval(treeNode, intervalId);
		}
		node.CollapseAll();
	}

	private void PopulateMachinesWithInterval(TreeNode treeNode, int intervalId)
	{
		var adapter = new ComponentsTableAdapter();
		var result = adapter.GetCpByInterval(intervalId);
		var dv = result.DefaultView;
		dv.Sort = "machineName";
		var sortedResult = dv.ToTable();
		if (sortedResult.Rows.Count > 0)
		{
			int machineID;
			List<int> machineIds = new List<int>();
			var machineNode = new TreeNode();
			foreach (DataRow row in sortedResult.Rows)
			{
				Int32.TryParse(row["machine_id"].ToString(), out machineID);
				if (!machineIds.Contains(machineID))
				{
					machineIds.Add(machineID);
					machineNode = new TreeNode(row["machineName"].ToString());
					int status_ID = ors.GetOilStatusByMachineID(machineID, sortedResult);
					machineNode.ImageUrl = HelperClass.GetOilIconByStatusID(status_ID.ToString());
					treeNode.ChildNodes.Add(machineNode);
				}
				var cpNode = new TreeNode(row["componentName"].ToString());
				cpNode.NavigateUrl = "oilreport.aspx?id=" + row["machine_id"] + "&component_id=" +
				                     row["component_id"];
				cpNode.Target = "report_content";
				machineNode.ChildNodes.Add(cpNode);
			}
		}
		treeNode.CollapseAll();
	}

	private bool HasTestIntervals(int clientId)
	{
		TestInterValTableAdapter adapter = new TestInterValTableAdapter();
		dtTestInterval = adapter.GetTestInterval(clientId);
		if (dtTestInterval.Rows.Count == 0) return false;
		return true;
	}

	private bool PopulateSubCompanies(TreeNode node)
	{
		ClientsTableAdapter adapter = new ClientsTableAdapter();
		DataTable dt = adapter.GetSubClients(ClientDetails.ClientID);
		if (dt.Rows.Count == 0) return false;
		foreach (DataRow dr in dt.Rows)
		{
			int subClientId;
			Int32.TryParse(dr["client_id"].ToString(), out subClientId);
			TreeNode subClientNode = new TreeNode(dr["clientName"].ToString());
			node.ChildNodes.Add(subClientNode);
			PopulateSites(subClientNode, subClientId);
		}
		return true;
	}
}




